package com.heima.xxlJob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jack
 * @data 2023 10:26
 */
@Component
@Slf4j
public class QuickStartJob {

    @Value("${xxl.job.executor.port}")
    private String port;

    @XxlJob("quickstartHandler")
    public void quickstart() {
        log.info("我被执行了...." + port);
    }


    //需求：设计一个分片广播：让两个节点共同处理1万个发放优惠券的任务,每个节点处理5000个
    @XxlJob("shardFanoutHandler")
    public void shardFanout() {
        //1. 拿到1万个任务
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 10000; i++) {
            list.add("第" + i + "张优惠券");
        }
        
        
        //2. 开始分片发放优惠券
        //2.1 拿到当前分片索引
        int shardIndex = XxlJobHelper.getShardIndex();
        //2.2 拿到当前分片总数
        int shardTotal = XxlJobHelper.getShardTotal();

        //3. 对任务进行分片处理
        for (int i = 0; i < list.size(); i++) {
            if (i % shardTotal == shardIndex){
                log.info(port+"分片处理了："+list.get(i) );
            }
        }

    }

}
